<template>
  <div class="app-container">
    <div class="filter-container">
      <statisSearchBar :start-date="searchForm.startDate" :end-date="searchForm.endDate" :showp-pf-channel="true" @transferFilter="handleFilter" />
      <el-button :loading="downloadLoading" type="primary" icon="el-icon-download" class="filter-item" @click="handleDownload()">导出</el-button>
    </div>
    <el-table v-loading="listLoading" :data="list" class="mt-10" border>
      <el-table-column label="注册日期" prop="date" width="110px" align="center"></el-table-column>
      <el-table-column label="注册人数" prop="num" width="98px" align="center"></el-table-column>
      <el-table-column label="至今LTV" prop="total" width="98px" align="center"></el-table-column>
      <el-table-column v-for="(day, index) in headList" :key="index" align="center" width="98px" :label="day+'日LTV'">
        <template slot-scope="scope">
          <div class="pre-formatted">{{ scope.row.ltv[day] }}</div>
        </template>
      </el-table-column>

    </el-table>
  </div>
</template>

<script>
import StatisSearchBar from '@/components/StatisSearchBar'
import { getLtv } from '@/api/statis'

export default {
  name: 'LTV',
  components: { StatisSearchBar },
  data() {
    return {
      list: [],
      headList: [],
      total: 0,
      listLoading: false,
      downloadLoading: false,
      searchForm: {
        startDate: new Date(Date.now() - 86400000 * 10),
        endDate: new Date()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleFilter(query) {
      this.searchForm = query
      this.getList()
    },
    async getList() {
      this.listLoading = true
      const res = await getLtv(this.searchForm)
      this.listLoading = false
      this.list = res.data.items
      this.headList = res.data.days
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['注册日期', '注册人数', '至今LTV', '1日LTV', '2日LTV', '3日LTV', '4日LTV', '5日LTV', '6日LTV', '7日LTV', '14日LTV', '21日LTV', '30日LTV', '60日LTV', '90日LTV', '180日LTV', '300日LTV']
        const filterVal = ['date', 'num', 'total', 1, 2, 3, 4, 5, 6, 7, 14, 21, 30, 60, 90]
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'ltv统计'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j > 0) {
          return v['ltv'][j]
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>

<style>
  .pre-formatted {
    white-space: pre-wrap;
  }
</style>
